package com.zb.repository;

import com.alibaba.fastjson.JSON;
import com.zb.dto.DeviceDTO;
import joptsimple.internal.Strings;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class DeviceRepository {

    @Autowired
    private RestHighLevelClient client;

    public List<DeviceDTO> search(Integer index, Integer size, String deviceId, Integer status, String tag) {

        SearchRequest searchRequest = new SearchRequest("devices");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.from((index-1)*size);
        searchSourceBuilder.size(size);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (status!=null){
            //状态（在线状态和告警状态）  0：在线  1：离线  2：一般告警  3：严重告警
            switch (status){
                case 0:
                    boolQueryBuilder.must(QueryBuilders.termQuery("online",true));
                    break;
                case 1:
                    boolQueryBuilder.must(QueryBuilders.termQuery("online",false));
                    break;
                case 2:
                    boolQueryBuilder.must(QueryBuilders.termQuery("level",1));
                    break;
                case 3:
                    boolQueryBuilder.must(QueryBuilders.termQuery("level",2));
                    break;
            }
        }
        if (!Strings.isNullOrEmpty(deviceId)){
            boolQueryBuilder.must(QueryBuilders.wildcardQuery("deviceId",deviceId+"*"));
        }
        if (!Strings.isNullOrEmpty(tag)){
            boolQueryBuilder.must(QueryBuilders.wildcardQuery("tag","*"+tag+"*"));
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        //执行查询获取响应
        SearchResponse searchResponse = null;
        try {
            searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取响应数据
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        List<DeviceDTO> list = new ArrayList<>();
        for (SearchHit searchHit : searchHits) {
            String id = searchHit.getId();
            String json = searchHit.getSourceAsString();
            DeviceDTO deviceDTO = JSON.parseObject(json, DeviceDTO.class);
            deviceDTO.setDeviceId(id);
            list.add(deviceDTO);
        }
        return list;
    }

    /**
     * 人工修改设备的状态
     * @param deviceId
     * @param status
     */
    public void updateStatus(String deviceId,Boolean status){
        UpdateRequest updateRequest = new UpdateRequest("devices",deviceId);
        updateRequest.doc("status",status);
        try {
            UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
            System.out.println(updateResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 人工修改设备标签
     * @param deviceId
     * @param tag
     */
    public void updateTag(String deviceId,String tag){
        UpdateRequest updateRequest = new UpdateRequest("devices",deviceId);
        updateRequest.doc("tag",tag);
        try {
            UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
            System.out.println(updateResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 系统自动修改设备状态
     * @param deviceId
     * @param online
     */
    public void updateOnline(String deviceId,Boolean online){
        UpdateRequest updateRequest = new UpdateRequest("devices",deviceId);
        updateRequest.doc("online",online);
        try {
            UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
            System.out.println(updateResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 系统自动修改设备标签
     * @param deviceId
     * @param alarm
     * @param alarmName
     * @param level
     */

    public void  updateAlarm(String deviceId,Boolean alarm,String alarmName,Integer level){
        UpdateRequest updateRequest = new UpdateRequest("devices",deviceId);
        updateRequest.doc("alarm",alarm,
                "alarmName",alarmName,
                "level",level);
        try {
            UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
            System.out.println(updateResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 添加设备，根据上报的数据 ，后台自动添加，没有设备的手动添加页面
     * @param deviceDTO
     */
    public void addDevice(DeviceDTO deviceDTO){
        if(deviceDTO ==null) {
            return;
        }
        IndexRequest indexRequest = new IndexRequest("devices");
        indexRequest.id(deviceDTO.getDeviceId());
        String json = JSON.toJSONString(deviceDTO);
        Map<String,Object> map = JSON.parseObject(json, Map.class);
        indexRequest.source(map);

        try {
            IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
            System.out.println(indexResponse.status());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public DeviceDTO searchDeviceById(String deviceId){
        DeviceDTO deviceDTO = null;
        //查询请求
        SearchRequest searchRequest = new SearchRequest("devices");
        //创建查询构建
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.termQuery("_id",deviceId));
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = null;
        //执行请求获取响应
        try {
            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取响应数据
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit searchHit : searchHits) {
            String id = searchHit.getId();
            String json = searchHit.getSourceAsString();
            deviceDTO = JSON.parseObject(json,DeviceDTO.class);
            deviceDTO.setDeviceId(id);
        }
        return deviceDTO;
    }
}
